// 根据access__token获取票据
var express = require("express");
var router = express.Router();
const { getAccessToken } = require("../../accesstoken");
const request = require("request");
const cache = require("memory-cache");
const config = require("../../config");
const jsSHA1 = require("jssha/dist/sha1");
const ticketCache = new cache.Cache();
router.get("/", function (req, res, next) {
  function getConfig(ticket, url) {
    var noncestr = Math.random().toString(36).substr(2, 15);
    var timestamp = parseInt(new Date().getTime() / 1000) + "";
    var str =
      "jsapi_ticket=" +
      ticket +
      "&noncestr=" +
      noncestr +
      "&timestamp=" +
      timestamp +
      "&url=" +
      url;
    var shaObj = new jsSHA1("SHA-1", "TEXT");
    shaObj.update(str);
    var signature = shaObj.getHash("HEX");
    return {
      appId: config.appID,
      timestamp: timestamp,
      nonceStr: noncestr,
      signature: signature,
    };
  }
  if (ticketCache.get("ticket")) {
    const obj = getConfig(ticketCache.get("ticket"), req.query.url);
    res.send(obj);
    return;
  }
  getAccessToken((body) => {
    let access_token = body.access_token;
    if (access_token) {
      request(
        "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" +
          access_token +
          "&type=jsapi",
        function (error, response, body) {
          if (!error && response.statusCode == 200) {
            ticketCache.put("ticket", JSON.parse(body).ticket, 7000 * 1000);
            res.send(getConfig(JSON.parse(body).ticket, req.query.url));
          } else {
            res.send(response);
          }
        }
      );
    } else {
      res.send(body);
    }
  });
});

module.exports = router;
